const db = require('../../../db/index');
const myDate = require('../../tool/myDate');
const arrMethod = require('../../tool/arrMethod');
const addAttendance = require('../salary/addAttendance');

exports.addCompany = (toDay) => {
	// 查询当天所有考勤的用户
	// let toDay = myDate.toDay();
	const sql = 'select * from attendance where day_date=?';
	db.query(sql, toDay, (err, results) => {
		// 计算上班和调休的人数
		let c_office_number = 0;
		let c_rest_number = 0;
		for (let i = 0; i < results.length; i++) {
			if (results[i].office_status == 0) {
				c_office_number++;
			};
			if (results[i].office_status == 1) {
				c_rest_number++;
			}
		}
		let c_total_number = c_office_number + c_rest_number;
		// 查寻公司考勤表中重复的部分
		const sql = 'select * from company_attendance where c_day_date=?';
		db.query(sql, toDay, (err, results) => {
			// 如果length为0 说明 没有重复的，正常添加
			if (results.length === 0) {
				// 加入到公司考勤表中
				const sqlStr = c_office_number + ',' + c_rest_number + ',' + "'"+ toDay + "'" + ',' + c_total_number;
				const sql = 'insert into company_attendance(c_office_number, c_rest_number, c_day_date, c_total_number) values(' + sqlStr + ')';
				db.query(sql, (err, results) => {
					console.log('更新公司考勤表成功', toDay);
					// 添加或更新考勤表
					addAttendance.addAttendance();
				});
				// 不为0 ，说明存在重复的，需要用更新语句
			} else {
				const bodyId = results[0].id;
				const sql = 'update company_attendance set c_office_number=?, c_rest_number=?, c_total_number=? where id=?';
				db.query(sql,[c_office_number, c_rest_number, c_total_number, bodyId] ,(err, results) => {
					console.log('更新公司考勤表成功',toDay);
					// 添加或更新考勤表
					addAttendance.addAttendance();
				});
			}
		})
	});
}